package com.yoomiito.app.ui.college.detail

import cn.droidlover.xdroidmvp.net.ApiException
import cn.droidlover.xdroidmvp.net.ApiSubscriber
import cn.droidlover.xdroidmvp.net.BaseModel
import cn.droidlover.xdroidmvp.net.XApi
import com.alibaba.fastjson.JSONObject
import com.yoomiito.app.base.AppConfig
import com.yoomiito.app.base.BaseActPresenter
import com.yoomiito.app.model.bean.GoodsDetail
import com.yoomiito.app.model.colleage.SubjectDetailInfo
import com.yoomiito.app.model.colleage.SubjectTableInfo
import com.yoomiito.app.model.my.MyRemainMoneyInfo
import com.yoomiito.app.model.order.CreateOrderInfo
import com.yoomiito.app.net.YmApi
import com.yoomiito.app.utils.*
import io.reactivex.Flowable
import io.reactivex.functions.BiFunction
import io.reactivex.functions.Function
import okhttp3.RequestBody
import org.reactivestreams.Publisher
import java.util.LinkedHashMap

class SubjectDetailPresenter(appConfig: AppConfig) : BaseActPresenter<SubjectDetailActivity>(appConfig) {

    fun getSubjectInfo(id: Long) {
        Flowable.zip(YmApi.getYmService().getSubjectDetail(id),
                YmApi.getYmService().getSubjectTable(id),
                BiFunction<BaseModel<GoodsDetail>, BaseModel<List<SubjectTableInfo>>, SubjectDetailInfo> { goodDetail, tableInfo ->

                    if (!ApiException.codes.contains(goodDetail.code)) {
                        throw ApiException(goodDetail.code, goodDetail.msg)
                    } else {
                        SubjectDetailInfo(goodDetail.data, tableInfo.data)
                    }
                })
                .compose(v.bindToLifecycle())
                .compose(XApi.getScheduler())
                .doOnError {
                    val error = it as ApiException
                    v.error(error.msg)
                }
                .subscribe({
                    v.setData(it)
                },{})
    }

    /**
     * 上传20s记录
     */
    fun postTwentySeconds(id: Long) {
        YmApi.getYmService().postTwentySecond(id)
                .compose(v.bindToLifecycle())
                .compose(XApi.getApiTransformerNoData<BaseModel<*>>())
                .compose(XApi.getScheduler<BaseModel<*>>())
                .subscribe(object : ApiSubscriber<BaseModel<*>>() {
                    override fun onSuccess(t: BaseModel<*>?) {

                    }

                    override fun onFail(error: ApiException?) {
                    }

                })

    }

    /**
     * 申请成为VIP
     */
    fun requestVIP(id: Long) {
        YmApi.getYmService().requestVip(id)
                .compose(v.bindToLifecycle())
                .compose(XApi.getApiTransformerNoData<BaseModel<*>>())
                .compose(XApi.getScheduler<BaseModel<*>>())
                .subscribe(object : ApiSubscriber<BaseModel<*>>(handleException()) {
                    override fun onSuccess(t: BaseModel<*>?) {
                        v.requestVIPResult(true)
                    }

                    override fun onFail(error: ApiException?) {
                        v.requestVIPResult(false)
                    }

                })
    }


    fun createOrder(productId: Long) {
        val params = LinkedHashMap<String, Any>()
        params["product_id"] = productId
        params["consignee"] = UserInfoConfig.getUser().name
        params["area_id"] = 330000
        params["area_id2"] = 330100
        params["area_id3"] = 330127
        params["area_name"] = "浙江省杭州市淳安县"
        params["mobile"] = UserInfoConfig.getTel()
        params["address"] = "杭州千岛湖望岛度假酒店"
        params["note"] = ""
        params["num"] = 1
        val body = RequestBody.create(YmApi.JSON, JSONObject.toJSONString(params))
        YmApi.getYmService()
                .createOrder(body)
                .compose(v.bindToLifecycle())
                .compose(XApi.getApiTransformerData())
                .flatMap { t ->
//                    v.mPayOrderId = t.orderid
                    v.mPayMoney = t.amount_paid
                    v.mOrderType = t.vip_order_type
                    YmApi.getYmService().moneyAgent
                }
                .compose(XApi.getApiTransformerData())
                .compose(XApi.getScheduler())
                .subscribe(object : ApiSubscriber<MyRemainMoneyInfo>(handleException()) {
                    override fun onSuccess(data: MyRemainMoneyInfo) {
                        v.dismissLoading()
                        data.isShowYoumi = false
                        v.setYouMi(data)
//                        v.showPayDialog()
                        //                        getV().orderId = orderResult.getOut_trade_no();
                        //                        PayTypeUtils.wxPay(orderResult);
                    }

                    override fun onFail(error: ApiException) {
                        v.dismissLoading()
                    }
                })
    }

    fun queryOrder(orderId: String, pay_type: String) {
        if (NetworkUtils.checkNetPermission(v)) {
            return
        }
        val eventMessage = EventMessage()
        YmApi.getYmService()
                .quseryOrderStatus(orderId, pay_type)
                .compose(v.bindToLifecycle())
                .compose<BaseModel<*>>(XApi.getApiTransformerNoData<BaseModel<*>>())
                .compose<BaseModel<*>>(XApi.getScheduler<BaseModel<*>>())
                .subscribe(object : ApiSubscriber<BaseModel<*>>(handleException()) {
                    override fun onSuccess(baseModel: BaseModel<*>) {
                        eventMessage.code = AllCode.Success
                        v.payResult(eventMessage)
                    }

                    override fun onFail(error: ApiException) {
                        eventMessage.code = AllCode.Fail
                        v.payResult(eventMessage)
                    }
                })
    }
}